<?php
namespace app\restaurant\model;

use app\BaseModel;
use think\facade\Db;

class OrderGoods extends BaseModel
{
    //定义表名
    protected $name = 'longbing_card_restaurant_order_goods';



    protected $append = [

        'feeding_text',

        'singe_pay_price',

        'refund_num'
    ];


    /**
     * @param $value
     * @param $data
     * @功能说明:已经退款的数量
     * @author chenniang
     * @DataTime: 2020-11-17 15:43
     */
    public function getRefundNumAttr($value,$data){

        if(!empty($data['id'])){

            $refund_model = new RefundOrder();

            $num = $refund_model->goodsNum($data['id']);

            return $num;

        }

    }



    /**
     * @author chenniang
     * @DataTime: 2020-11-16 15:23
     * @功能说明:单价
     */
    public function getSingePayPriceAttr($value,$data){

        if(isset($data['pay_price'])&&isset($data['goods_num'])){

            return round($data['pay_price']/$data['goods_num'],2);

        }

    }



    /**
     * @author chenniang
     * @DataTime: 2020-10-22 17:31
     * @功能说明:加料
     */

    public function getFeedingTextAttr($value,$data){

        if(!empty($data['id'])){

            $arr = Db::name('longbing_card_restaurant_feeding_order')->where(['order_goods_id'=>$data['id']])->column('title');

            return !empty($arr)?implode('+',$arr):'';

        }

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:04
     * @功能说明:添加
     */
    public function orderAdd($order,$list){

        $spe_model = new SpePrice();

        foreach ($list as $value){

            $insert['uniacid']     = $order['uniacid'];

            $insert['order_id']    = $order['id'];

            $insert['user_id']     = $order['user_id'];

            $insert['pay_type']    = $order['pay_type'];

            $insert['goods_id']    = $value['goods_id'];

            $insert['goods_name']  = $value['title'];

            $insert['goods_img']   = $value['cover'];

            $insert['goods_num']   = $value['num'];
            //可退款数量
            $insert['can_refund_num'] = $value['num'];

            $insert['norms']       = $value['spe_name'];

            $insert['goods_price'] = $value['price'];

            $insert['cost_price']  = $value['cost_price'];

            $insert['norms_id']    = $value['spe_id'];

            $insert['store_id']    = $order['store_id'];

            $insert['member_price']= $value['member_price'];
            //折扣商品价格(含加料)
            $insert['pay_price']   = round($value['true_price']*$value['num'],2);
            //餐盒费
            $insert['lunch_price']   = round($value['lunch_price']*$value['num'],2);
            //加料费
            $insert['feeding_price'] = round($value['feeding_price']*$value['num'],2);

            $insert['weight']      = $value['weight']*$value['num'];

            $insert['create_time'] = time();

            $insert['confirm']     = $order['order_type']==1?0:1;
            //加菜次数
            $insert['add_foods_time'] = $order['add_foods_time'];

            $insert['text'] = $order['order_text'];
            //增加订单
            $res = $this->insert($insert);

            if($res!=1){

                return ['code'=>'500','msg'=>'生成订单失败'];
            }
            $order_goods_id = $this->getLastInsID();
            //加料
            $this->addFeeding($order_goods_id,$value['feeding'],$order['uniacid']);
            //商品规格信息
            $spe = $spe_model->dataInfo(['id'=>$value['spe_id']]);
            //检查库存
            if($spe['stock']<$value['num']){

                return ['code'=>'500','msg'=>'商品:'.$value['title'].'库存不足'];

            }

            $stock = $value['num'];

            $dis = [];

            $dis[] = ['id','=',$value['spe_id']];

            $dis[] = ['stock','>=',$value['num']];

            $dis[] = ['create_time','=',$spe['create_time']];
            //检查库存
            $res   = $spe_model->where($dis)->update(['stock'=>Db::raw("stock-$stock"),'create_time'=>$spe['create_time']+1]);

            if($res!=1){

                return ['code'=>'500','msg'=>'下单人数过多，请重新下单！'];
            }
            //删除购物车
            $car_model = new Car();

            $car_model->where(['id'=>$value['car_id']])->delete();

            $goods_model = new Goods();
            //商品信息
            $goods = $goods_model->goodsInfo(['id'=>$value['goods_id']]);

            $update = [
                //加销量
                'true_sale_num' => $goods['true_sale_num'] + $value['num'],
                //减销售额
                'sale_cash'     => round($goods['sale_cash']+$insert['pay_price'],2),
            ];

            $res = $goods_model->where(['id'=>$value['goods_id']])->update($update);

        }

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-11-12 14:31
     * @功能说明:拼接退款子订单
     */
    public function refundOrderGoods($order_goods){

        $order_goods_model = new OrderGoods();

        $data = [];

        foreach ($order_goods as $k=>$v){

            $data[$k] = $order_goods_model->orderInfo(['id'=>$v['order_goods_id']]);

            $data[$k]['o_goods_num'] = $data[$k]['goods_num'];

            $data[$k]['goods_num']   = $v['goods_num'];


        }

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-10-23 16:05
     * @功能说明:取消订单归还库存
     */
    public function refundOrder($data){

        foreach ($data as $v){
            //修改子订单的状态
            if((!empty($v['o_goods_num'])&&$v['o_goods_num']==$v['goods_num'])||empty($v['o_goods_num'])){

                $this->orderUpdate(['id'=>$v['id']],['pay_type'=>-1,'refund'=>2,'can_refund_num'=>0]);
            }
            //归还库存
            $spe_model = new SpePrice();
            //商品规格信息
            $spe = $spe_model->dataInfo(['id'=>$v['norms_id']]);

            $stock = $v['goods_num'];

            $dis   = [];

            $dis[] = ['id','=',$spe['id']];

            $dis[] = ['create_time','=',$spe['create_time']];
            //检查库存
            $res   = $spe_model->where($dis)->update(['stock'=>Db::raw("stock+$stock"),'create_time'=>$spe['create_time']+1]);

            if($res!=1){

                return ['code'=>'500','msg'=>'退款人数过多，请重新下单！'];

            }
            $goods_model = new Goods();
            //商品信息
            $goods = $goods_model->goodsInfo(['id'=>$v['goods_id']]);

            $update = [
                //减销量
                'true_sale_num' => ($goods['true_sale_num'] - $v['goods_num'])>0?$goods['true_sale_num'] - $v['goods_num']:0,
                //减销售额
                'sale_cash'     => ($goods['sale_cash'] - $v['singe_pay_price']*$v['goods_num'])>0?($goods['sale_cash'] - $v['singe_pay_price']*$v['goods_num']):0,
            ];

            $res = $goods_model->where(['id'=>$v['goods_id']])->update($update);

        }

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-10-23 09:48
     * @功能说明:加料
     */
    public function addFeeding($id,$feeding,$uniacid){

        if(!empty($feeding)){

            foreach ($feeding as $value){

                $data['uniacid'] = $uniacid;

                $data['order_goods_id'] = $id;

                $data['title'] = $value['title'];

                $data['price'] = $value['price'];

                Db::name('longbing_card_restaurant_feeding_order')->insert($data);

            }

        }

        return true;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:05
     * @功能说明:编辑
     */
    public function orderUpdate($dis,$data){

//        $data['update_time'] = time();

        $res = $this->where($dis)->update($data);

        return $res;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:06
     * @功能说明:列表
     */
    public function orderList($dis){

        $file = ['goods_name','goods_img','goods_num','norms','norms_id','goods_price','member_price','id'];

        $data = $this->where($dis)->order('id desc')->select()->toArray();

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-09-29 11:43
     * @功能说明:详情
     */
    public function orderInfo($dis){

        $data = $this->where($dis)->find();

        return !empty($data)?$data->toArray():[];

    }


    /**
     * @author chenniang
     * @DataTime: 2020-11-16 10:01
     * @功能说明:检测商品
     */
    public function checkOrderGoods($order_goods,$store_id,$user_id,$order_id=0){

        $goods_model = new Goods();

        $car_model   = new Car();

        foreach ($order_goods as $v){

            $goods = $goods_model->where(['id'=>$v['goods_id'],'status'=>1])->field('title,limit_status,limit,buy_start')->find();

            if(empty($goods)){

                return ['code'=>500,'msg'=>'商品已经下架'];
            }

            $dis = [

                'user_id' => $user_id,

                'goods_id'=> $v['goods_id'],

                'store_id'=> $store_id
            ];

            $goods_num = $car_model->where($dis)->sum('num');

            if(!empty($order_id)){

                $order_goods_num = $this->where(['order_id'=>$order_id,'goods_id'=>$v['goods_id']])->sum('goods_num');

                $goods_num+= $order_goods_num;
            }

            if($goods->limit_status==1&&$goods->limit<$goods_num){

                return ['code'=>500,'msg'=>$goods->title.'限购'.$goods->limit.'件'];

            }

            if($goods->buy_start>$goods_num){

                return ['code'=>500,'msg'=>$goods->title.'起购'.$goods->buy_start.'件'];

            }

        }

        return true;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-04 14:56
     * @功能说明:订单列表的商品列表 用于优惠券抵扣
     */
    public function orderGoodsListCoupon($order_id){

        $dis = [

            'a.order_id' => $order_id
        ];

        $data = $this->alias('a')
                ->join('longbing_card_restaurant_goods b','a.goods_id = b.id')
                ->where($dis)
                ->field('a.goods_id,b.cate_id,a.pay_price as true_price,a.id,a.feeding_price,a.goods_num as num')
                ->group('a.id')
                ->select()
                ->toArray();

        if(!empty($data)){

            foreach ($data as &$v){

                $v['true_price'] = round($v['true_price']/$v['num'],2);

            }
        }

        return $data;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-05 13:07
     * @功能说明:堂食订单商品列表
     */
    public function houseOrderGoods($order_id){

        $dis = [

            'order_id' => $order_id
        ];

        $goods_model = new Goods();

        $add_time = $this->where($dis)->field('add_foods_time,text,create_time')->group('add_foods_time')->order('add_foods_time desc')->select()->toArray();

        foreach ($add_time as &$value){

            $dis['add_foods_time'] = $value['add_foods_time'];

            $value['create_time']  = date('Y-m-d H:i:s',$value['create_time']);

            $value['list'] = $this->where($dis)->order('id desc')->select()->toArray();

            if(!empty($value['list'])){

                foreach ($value['list'] as $k=>$v){

                    $value['list'][$k]['buy_start'] =  $goods_model->where(['id'=>$v['goods_id']])->value('buy_start');

                }

            }

        }

        return $add_time;

    }











}